<?php

namespace app\teacher\controller\subject;

use app\common\controller\Frontend;
use app\common\enums\LearnMeansEnum;
use app\common\enums\LearnSubjectAntiForgettingStatusEnum;
use app\common\enums\SubjectKnowledgeStatusEnum;
use app\common\model\banxi\learn\LearnSubjectAntiForgetting as LearnSubjectAntiForgettingModel;
use app\common\model\banxi\subject\Subject as SubjectModel;
use app\common\model\banxi\subject\SubjectGrade as SubjectGradeModel;
use app\common\model\banxi\subject\SubjectKnowledge as SubjectKnowledgeModel;
use app\common\model\banxi\subject\SubjectQuestion as SubjectQuestionModel;
use app\common\model\banxi\learn\LearnSkRecord;
use app\common\service\learn\LearnSkRecordService;
use app\common\service\ImportService;
use think\db\exception\DbException;
use think\exception\ValidateException;
use think\facade\Validate;
use think\validate\ValidateRule;

class Question extends Frontend
{
    protected array $noNeedLogin = [];
    protected array $noNeedPermission = [];

    public function initialize(): void
    {
        parent::initialize();
        $this->model = new SubjectQuestionModel();
    }


    /**
     * 分页查询
     * @return void
     * @throws DbException
     */
    public function listPage(): void
    {
        $param = $this->request->param(['index', 'limit', 'orderBy', "query"]);
        //查询条件解析
        $where = get_query($param);
        //获取分页数据
        $pageParams = get_page_params($param);
        $knowledgeList = [];
        $list = $this->model->where($where)
            ->with([
                'subject' => function ($query) {
                    $query->field('id,name');
                }, 'subjectGrade' => function ($query) {
                    $query->field('id,name');
                }, 'knowledge' => function ($query) {
                    $query->field('id,pid,name');
                }])
            ->order(['id' => 'asc', 'sortNum' => 'desc'])
            ->paginate([
                'page' => $pageParams['page'],
                'list_rows' => $pageParams['limit'],
            ])->each(function ($item) {
                if (!empty($item['knowledge'])) {
                    if (!empty($item['knowledge']['pid'])) {
                        $pid = $item['knowledge']['pid'];
                        $pidKnowledge = SubjectKnowledgeModel::where(['id' => $pid, 'status' => SubjectKnowledgeStatusEnum::E1])->field('id,name')->find();
                        unset($item['knowledge']['pid']);
                        $pidKnowledge['children'] = $item['knowledge'];
                        $item['knowledge'] = $pidKnowledge;
                    } else {
                        $item['knowledge']['children'] = null;
                        unset($item['knowledge']['pid']);
                    }
                }
                $item['option'] = $item['option'] ? json_decode($item['option'], true) : [];
                $item['answer'] = $item['answer'] ? json_decode($item['answer'], true) : [];
            });
        $this->ok('操作成功', result_row($list));
    }

    /**
     * 分页Select查询
     * @return void
     * @throws DbException
     */
    public function listSelectPage(): void
    {
        $param = $this->request->param(['index', 'limit', 'orderBy', "query"]);
        //查询条件解析
        $where = get_query($param);
        //获取分页数据
        $pageParams = get_page_params($param);
        $list = $this->model->where($where)
            ->field('id,name')
            ->order(['id' => 'asc', 'sortNum' => 'desc'])
            ->paginate([
                'page' => $pageParams['page'],
                'list_rows' => $pageParams['limit'],
            ]);
        $this->ok('操作成功', result_row($list));
    }

    /**
     * 查询
     * @return void
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     */
    public function get()
    {
        $param = $this->request->param(["query" => []]);
        if (empty($param['query'])) {
            $this->fail('请传递你要查询的记录');
        }
        $where = get_query($param);

        $info = $this->model->with([
            'subject' => function ($query) {
                $query->field('id,name');
            }, 'subjectGrade' => function ($query) {
                $query->field('id,name');
            }])->where($where)->find();
        if (empty($info)) {
            $this->fail('记录不存在');
        }
        $info['option'] = $info['option'] ? json_decode($info['option'], true) : [];
        $info['answer'] = $info['answer'] ? json_decode($info['answer'], true) : [];
        $this->ok('操作成功', $info);
    }


    /**
     * 随机题
     * @return void
     */
    public function randomQuestion()
    {
        $param = $this->request->param(['subjectKnowledgeId' => 0, 'randomNum' => 1]);
        try {
            $validate = Validate::rule([
                'subjectKnowledgeId' => ValidateRule::isRequire(null, '请选择你要查询知识点'),
                'randomNum' => ValidateRule::isRequire(null, '请设置你要随机的数量'),
            ]);
            if (!$validate->check($param)) throw new ValidateException($validate->getError());
            $res = $this->model->randomQuestion($param['subjectKnowledgeId'], $param['randomNum']);
        } catch (ValidateException $exception) {
            $this->fail($exception->getMessage());
        }
        $this->ok('成功', $res);
    }

    /*
     * 布置课后作业
     * */
    public function setQuestion()
    {
        $param = $this->request->param(['question' => '','id'=>0]);
        try {
            $validate = Validate::rule([
                'id' => ValidateRule::isRequire(null, '上课记录不能为空'),
                'question' => ValidateRule::isRequire(null, '请选择题目')
            ]);
            if (!$validate->check($param)) throw new ValidateException($validate->getError());
            $LearnSkRecordModel = new LearnSkRecord();
            $LearnSkRecordModel->updateAfterClassQuestion($param['id'],$param['question']);
        } catch (ValidateException $exception) {
            $this->fail($exception->getMessage());
        }
        $this->ok('操作成功', [], self::NOTIFICATION);
    }


    /*
     * 开始答题
     * */
    public function startQuestion()
    {
        $skRecordId = $this->request->post('skRecordId');
        $exerciseType = $this->request->post('exerciseType');
        $subjectAntiForgettingId = $this->request->post('subjectAntiForgettingId');
        $subjectTeachId = $this->request->post('subjectTeachId',0);
        $subjectTeachChapterId = $this->request->post('subjectTeachChapterId',0);

        if (!in_array($exerciseType,[1,2,3])){
            $this->fail('请选择做题类型');
        }
        $trainerId = $this->auth->id;
        $studentId = null;
        $learnMeans = LearnMeansEnum::E2; // 默认为练习模式（对应 LearnMeans.E2）

        // 如果提供了上课记录ID
        if ($skRecordId) {
            // 查询上课记录
            $learnSkRecord = LearnSkRecord::where('id', $skRecordId)->find();

            // 验证上课记录是否存在
            if (empty($learnSkRecord)) {
                $this->fail('上课记录不存在');
            }

            // 验证教练ID是否匹配
            if ($learnSkRecord['trainerId'] != $trainerId) {
                $this->fail('上课记录不存在');
            }

            // 获取学生ID
            $studentId = $learnSkRecord['studentId'];
            if ($subjectAntiForgettingId){
                $LearnSubjectAntiForgettingModel = new LearnSubjectAntiForgettingModel();
                $record = $LearnSubjectAntiForgettingModel
                    ->where(['id'=>$subjectAntiForgettingId,'trainerAntiForgettingId'=>$trainerId])
                    ->find();
                if (!$record) {
                    $this->fail('抗遗忘记录不存在');
                }
                if ($record['status'] != LearnSubjectAntiForgettingStatusEnum::E2){
                    $this->fail('抗遗忘状态有误');
                }
                $learnMeans = LearnMeansEnum::E3; // 设置为抗遗忘模式（对应 LearnMeans.E3）
            }else{
                $learnMeans = LearnMeansEnum::E1; // 设置为教学模式（对应 LearnMeans.E1）
            }
        }
        $skRecordId = $skRecordId ? $skRecordId : null;
        $LearnSkRecordService = new LearnSkRecordService();
        $result = $LearnSkRecordService->startSubjectQuestion($skRecordId, $studentId, $trainerId, $learnMeans,$exerciseType,$subjectTeachId,$subjectTeachChapterId,$subjectAntiForgettingId);

        if (!$result){
            $this->fail($LearnSkRecordService->getError());
        }
        $this->ok('提交成功', $result);
    }

    /*
     * 答案提交
     * */
    public function answerQuestion()
    {
        $recordId = $this->request->post('recordId');
        $answerList = $this->request->post('answerList');

        if (!$recordId){
            $this->fail('记录id不能为空');
        }
        if (!$answerList){
            $this->fail('提交答案不能为空');
        }
        $trainerId = $this->auth->id;

        $LearnSkRecordService = new LearnSkRecordService();
        $result = $LearnSkRecordService->answerSubjectQuestion($recordId, $trainerId, null, $answerList);
        if (!$result){
            $this->fail($LearnSkRecordService->getError());
        }
        $this->ok('操作成功', [], self::NOTIFICATION);
    }
}
